from rest_framework import serializers
from user.models import User


class RegisterSerializer(serializers.ModelSerializer):
    allow = serializers.CharField(write_only=True)
    password1 = serializers.CharField(max_length=20,min_length=8,write_only=True)

    class Meta:
        model = User
        fields = '__all__'

    extra_kwargs={
        'username':{
            'max_length':20,
            'min_length':5
        },
        'password': {
            'max_length': 20,
            'min_length': 8,
            'write_only':True
        }
    }


    def validate(self, attrs):
        '''
        多字段验证
        :param attrs:
        :return:
        '''
        if attrs['password']!=attrs['password1']:
            raise serializers.ValidationError('密码不一致')

        if attrs['allow']!='on':
            raise serializers.ValidationError('未同意协议')

        return attrs

    def create(self, validated_data):
        user = User.objects.create_user(username = validated_data['username'],password = validated_data['password'],email = validated_data['email'])

        return user

